import { Context } from "jsr:@oak/oak/context";
import { Next } from "jsr:@oak/oak/middleware";
import { AppError } from "../errors/AppError.ts";
import type { ApiResponse } from "../shared/types.ts";

export async function errorMiddleware(ctx: Context, next: Next) {
  try {
    await next();
  } catch (err) {
    console.error('Error:', err);

    const errorResponse: ApiResponse = {
      success: false,
      message: err instanceof AppError ? err.message : "服务器内部错误",
      code: err instanceof AppError ? err.code : "INTERNAL_SERVER_ERROR"
    };

    ctx.response.status = err instanceof AppError ? err.status : 500;
    ctx.response.body = errorResponse;
  }
} 